package com.jeesite.modules.st.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.jeesite.modules.st.pojo.PrintHeader;
import com.jeesite.modules.st.pojo.PrintTable;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

@Component
public class PdfUtils {
    @Value("${tpl_path}")
    String tplPath;
    @Value("${out_pdf_path}")
    String outPdfPath;

    /**
     * 贴纸
     */
    public static class Paster {
        public float width;
        public float height;
    }

    public void pdfTZ(Map<String, Object> map, String outFileName) {
        Paster p = new Paster();
        p.width = 258F;
        p.height = 143F;
        String html = freemarker("ycl.ftl", map);
//        FileOutputStream fileOutputStream = null;
//        try {
//            fileOutputStream = new FileOutputStream("ycl.html");
//            fileOutputStream.write(html.getBytes());
//            fileOutputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        html2pdf(html, p, outPdfPath + outFileName);
    }

    public void main(String[] args) throws IOException {
        Map<String, Object> map = new HashMap<>();
        PrintHeader header = new PrintHeader();
        header.custom = "客户123";
        header.sendDate = "2020-12-12";
        header.customPhone = "1348";
        header.sendBillNo = "00123";//送货单号
        header.sendAddress = "地址。。。。。";
        header.businessMan = "熏悟空";
        header.deliveryArea = "火焰山";//交货区域
        header.sendCarNo = "car888";//送货车牌
        header.total = "10000";//合计
        header.barCode = "D:\\work\\java\\jeesite4\\root\\qr\\bar.png";//二维码
        map.put("header", header);
        List<PrintTable> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            PrintTable printTable = new PrintTable();
            printTable.billNo = "xs12222222-" + i;
            printTable.goodsName = "保育乐-" + i;
            printTable.unit = "KG";
            printTable.number = "1000";
            printTable.remarks = "";
            list.add(printTable);
        }
        map.put("list", list);
        String html = freemarker("sendBill.ftl", map);
        FileOutputStream fileOutputStream = new FileOutputStream("send.html");
        fileOutputStream.write(html.getBytes());
        fileOutputStream.close();
        html2pdf(html, null, "send-bill.pdf");
    }

    public String freemarker(String source, Map<String, Object> root) {
        Configuration cfg = new Configuration();
        StringWriter sw = new StringWriter();
        try {

//            cfg.setClassForTemplateLoading(this.getClass(), "/");//模板所在位置
            cfg.setDirectoryForTemplateLoading(new File(tplPath));
            Template template = cfg.getTemplate(source); //framemaker.ftl为要装载的模板
            // 设置对象包装器
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            // 设置异常处理器
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
            // 定义数据模型

            try {
                // 解释模板
                template.process(root, sw);  //将  名为root的Map  映射到  out 输出中
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    public void html2pdf(String html, Paster tz, String outFileName) {
//        A4尺寸（210x297mm，595x842像素），72分辨率的图，如果用PS直接改成300分辨率，印刷（A4尺寸）时，
        Document document = null;
        PdfWriter pdfWriter = null;
        try {
            if (tz != null) {
                document = new Document(new RectangleReadOnly(tz.width, tz.height), 0, 0, 0, 0);
            } else {
                document = new Document();
            }
            pdfWriter = PdfWriter.getInstance(document,
                    new FileOutputStream(outFileName));
            //此处设置的并没有起作用,不知道为什么
            document.addAuthor("author");
            document.addCreator("test");
            document.addSubject("评测结果");
            document.addCreationDate();
            document.addTitle("HTML to PDF");
            document.open();


            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
            //读取模板文件并且写入String中
//            InputStream in = new FileInputStream(htmlFile);
//            InputStreamReader isr = new InputStreamReader(in, "utf-8");
//            BufferedReader brd = new BufferedReader(isr);
//            StringBuffer sbf = new StringBuffer();
//            String line = "";
//            while((line=brd.readLine())!=null) {
//                sbf.append(line);
//            }
//            String htmlTemplete = sbf.toString();
//            //此处替换特定字符或者拼接html代码的处理
//            htmlTemplete = htmlTemplete.replaceAll("###TITLE###", "html转pdf");
//            htmlTemplete = htmlTemplete.replaceAll("###INTRODUCE###", "html转pdf测试");
            //模板不支持svg格式图片
            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(html.getBytes("UTF-8")), Charset.forName("utf8"), new AsianFontProvider());

            System.out.println("complete");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (document != null)
                //如果不关闭则会生成空的破损的pdf
                document.close();
        }
    }
}
